import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


# 定义网络类
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 定义第一层卷积层
        self.conv1 = nn.Conv2d(1, 6, kernel_size=3)
        # 定义第二层卷积层
        self.conv2 = nn.Conv2d(6, 16, kernel_size=3)
        # 定义三层全连接层
        self.fc1 = nn.Linear(16 * 6 * 6, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 注意：任意卷积层后面都要加上激活层、池化层
        # 卷积层1
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # 卷积层2
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)

        # 经过卷积层的处理后，张量的维度变成[batch_size, 16, 6, 6]，进入前需要调整张量的形状
        # 改变张量的维度
        x = x.view(-1, self.num_flat_features(x))
        # 全连接层1
        x = F.relu(self.fc1(x))
        # 全连接层2
        x = F.relu(self.fc2(x))
        # 全连接层3
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]
        num_features = 1
        for s in size:
            num_features *= s
        return num_features


net = Net()
# print(f"net:{net}")
params = list(net.parameters())
# print(f"params length:{len(params)}")
# print(f"params:{params[0].size()}")

input = torch.randn(1, 1, 32, 32)
# output = net(input)
# print(f"output:{output}")
# print(f"output.size:{output.size()}")

target = torch.randn(10)
target = target.view(1, -1)
criterion = nn.MSELoss()

# loss = criterion(output, target)
# print(f"loss:{loss}")
#
# print(f"loss.grad_fn:{loss.grad_fn}")

# # pytorch中首先要执行梯度清零操作
# net.zero_grad()
# print(f"conv1.bias.grad before backward:{net.conv1.bias.grad}")
#
# # 在pytorch中实现一次反向传播
# loss.backward()
# print(f"conv1.bias.grad after backward:{net.conv1.bias.grad}")

# 第一步导入优化器包
# 构建优化器
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 第二步：优化器梯度清零
optimizer.zero_grad()
# 第三步：执行网络计算并计算损失值
output = net(input)
loss = criterion(output, target)
# 第四步：反向传播
loss.backward()
# 第五步：优化器更新参数
optimizer.step()
print("训练完成")